import json

from QQLoginTool.QQtool import OAuthQQ
from django.contrib.auth import login
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.cart.utils import merge_cart_cookie_to_redis
from apps.oauth.models import OAuthQQUser
from apps.oauth.utils import generate_access_token, check_access_token
from apps.users.models import User
from meiduo import settings


class QQLoginView(View):
    def get(self, request):
        # 1.使用QQloginTool生成跳转链接
        # 1.1初始化OAuthQQ对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state="xxx")
        # 1.2获取qq登录扫码界面，扫码后得到Authorization Code
        login_url = oauth.get_qq_url()
        # 2.返回响应
        return JsonResponse({"code": 0, "login_url": login_url})


class OauthView(View):
    def get(self, request):
        # 1.获取code
        code = request.GET.get("code")
        print('code:', code)

        # 2.根据code获取token
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state="xxx")
        try:
            access_token = oauth.get_access_token(code)
            print('access_token:', access_token)

            # 3.根据token获取openid
            openid = oauth.get_open_id(access_token)
            print('openid:', openid)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "联网异常"})

        # 4.根据openid去数据库查询OAuthQQUser账号数据
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            print(e)
            # 4.1如果不存在，捕获异常，走没有绑定的逻辑，去绑定界面
            # 前端分析后，返回openid，key叫做access_token
            openid = generate_access_token(openid)
            print("openid---加密后：", openid)
            return JsonResponse({"code": 400, "access_token": openid})
        # 4.2如果存在，正常返回数据，做登录状态保持
        else:
            # session
            login(request, qquser.user)
            # cookie
            response = JsonResponse({"code": 0, "errmsg": "ok"})
            response.set_cookie("username", qquser.user.username)
            response1 = merge_cart_cookie_to_redis(request=request, user=qquser.user, response=response)

            return response1

    def post(self, request):
        # 1.接收请求
        body = request.body
        data_dict = json.loads(body)
        print(data_dict)
        # 2.获取请求参数：手机号，密码，短信验证码，openid
        password = data_dict.get("password")
        mobile = data_dict.get("mobile")
        sms_code = data_dict.get("sms_code")
        openid = data_dict.get("access_token")
        # 对openid进行解密获取源数据
        openid = check_access_token(openid)
        print("openid---解密后：", openid)
        # print(password, mobile, sms_code, openid)
        # 2.1验证参数
        if not all([password, mobile, sms_code, openid]):
            return JsonResponse({"code": 400, "errmsg": "参数不全"})

        # 3.根据手机号查询是否已经注册
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            print(e)
            # 4.如果没有注册，创建一个user对象，绑定用户
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)

        # 5.如果已经注册，进行密码验证，
        else:
            if not user.check_password(password):
                return JsonResponse({"code": 400, "errmsg": "账号或密码错误"})

        # 密码正确直接绑定用户和openid
        try:
            OAuthQQUser.objects.create(user=user, openid=openid)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "账号已经绑定，无法添加"})

        # 6.状态保持
        login(request, user)
        response = JsonResponse({"code": 0, "errmsg": "ok"})
        response.set_cookie("username", user.username)
        response1 = merge_cart_cookie_to_redis(request=request, user=user, response=response)

        # 7.返回响应
        return response1
